﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AuthorizationModule.cs" company="Anton Frattaroli">
//   Copyright (c) Anton Frattaroli. All rights reserved.
// </copyright>
// <summary>
//   Defines the AuthorizationModule implementation class of the IHttpModule interface to authorize access to requests.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Lidocaine.Service
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Web;
    using Lidocaine.BusinessLogic;
    using Lidocaine.BusinessObjects;
    
    /// <summary>
    /// Defines the AuthorizationModule class.
    /// </summary>
    public class AuthorizationModule : IHttpModule
    {
        /// <summary>
        /// Adds event handlers to the application lifecycle.
        /// </summary>
        /// <param name="context">The HttpApplication object for the request.</param>
        public virtual void Init(HttpApplication context)
        {
            context.AuthorizeRequest += new EventHandler(this.AuthorizationHandler);
        }

        /// <summary>
        /// Implements the standard Dispose() method of the IHttpModule interface.
        /// </summary>
        public virtual void Dispose()
        {
        }

        /// <summary>
        /// Authorizes requests.
        /// </summary>
        /// <param name="sender">The HttpApplication object for the request.</param>
        /// <param name="e">The EventArgs object for the request.</param>
        private void AuthorizationHandler(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            UserProfile currentUser = UserProfileManager.Current;
            string requestedPath = app.Request.Path;
            string requestedQuery = app.Request.Url.Query.TrimStart('?');
            if (!UserProfileManager.HasPermission(currentUser, requestedPath))
            {
                if (currentUser.IsAnonymous)
                {
                    app.Context.Response.Redirect(BusinessLogic.Environment.LogOnUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(requestedPath + (!string.IsNullOrEmpty(requestedQuery) ? "?" + requestedQuery : string.Empty)));
                    app.CompleteRequest();
                }
                else
                {
                    app.Context.Response.Redirect(BusinessLogic.Environment.ErrorUrl + "?Code=401");
                    app.CompleteRequest();
                }
            }
        }
    }
}